package com.ls.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {
    private static final String HOST = "127.0.0.1";
    private static final int POST = 6667;
    private Selector selector;
    private SocketChannel channel;
    private String name;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        channel = SocketChannel.open(new InetSocketAddress(HOST, POST));
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_READ);
        name = channel.getLocalAddress().toString();
        System.out.println(name + " is ok");
    }

    public void sendInfo(String info) {
        info = name + " 说 " + info;

        try {
            channel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void readInfo() {
        try {
            int realChannels = selector.select();
            if (realChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();

                    if (key.isReadable()) {
                        SocketChannel channel1 = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel1.read(byteBuffer);
                        String msg = new String(byteBuffer.array());
                        System.out.println(msg);
                    }
                    iterator.remove();
                }
            } else {
//                System.out.println("没有可用的通道");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        GroupChatClient groupChatClient = new GroupChatClient();

        new Thread() {
            public void run() {
                while (true) {
                    groupChatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();


        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();

            groupChatClient.sendInfo(s);
        }


    }
}
